<template>
    <div class="achievement-list-page">
        <el-card shadow="never" class="mt-4">
            <el-form class="filter" :inline="true">
                <el-form-item label="状态" prop="status">
                    <el-select
                        v-model="form.status"
                        placeholder="状态"
                        clearable
                        @change="onSubmit()">
                        <el-option
                            v-for="item in statusOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="关键词" prop="keyword">
                    <el-input v-model="form.keyword" placeholder class="input-width"></el-input>
                </el-form-item> -->
                <el-button type="primary" @click="onSubmit">搜索</el-button>
                <el-button type="primary" @click="onResetForm">重置</el-button>
                <div></div>
                <el-form-item label="筛选">
                    <Cascader ref="mycascader" @change="handleChange" :options="labelGroup" v-model="formCourseId"/>
                </el-form-item>
            </el-form>
            <el-button type="primary" @click="onAddClick">新增</el-button>
            <div class="mt-3" v-loading="loading">
                <el-table :data="data">
                    <el-table-column type="index" align="center" label="序号" width="50"/>
                    <el-table-column label="名称" prop="title"></el-table-column>
                    <el-table-column label="学习主题" prop="label"/>
                    <el-table-column label="状态" width="80">
                        <template slot-scope="{row}">
                            {{ row.status ? "上架" : "下架" }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="{row}">
                            <el-button type="text" @click="onEditClick(row)">编辑</el-button>
                            <el-button type="text" @click="onPublishClick(row)">
                                {{ row.status ? "下架" : "上架" }}</el-button>
                            <el-button
                                type="text"
                                @click="onDeleteClick(row)"
                                class="red-color">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-if="totalElements > 0" class="footer">
                <pagination
                ref="pagination"
                :currentPage="form.page"
                :pageSize="form.size"
                :handleCurrentChange="onCurrentChange"
                :handlePageSizeChange="onPageSizeChange"
                :totalElements="totalElements"
                ></pagination>
            </div>
        </el-card>
    </div>
</template>

<script>
import Cascader from '@/components/base/Cascader.vue';
import Pagination from '../../components/base/Pagination';
import TimeFormats from '../../helpers/TimeFormats';
import IndexNumber from '../../helpers/IndexNumber';

export default {
    components: {
        Pagination,
        Cascader,
    },
    mixins: [require('../../mixins/CacheQuery').default],
    data() {
        return {
            loading: false,
            data: [],
            form: {
                page: 1,
                size: 50,
                courseId: '', // 三级
                status: '',
                labelId: '', // 二级
                labelType: '', // 一级 --- 岗位角色等
            },
            formCourseId: '',

            statusOptions: [
                {id: true, name: '上架'},
                {id: false, name: '下架'},
            ],
            totalElements: 0,
            courseOptions: [],
            labelGroup: [
                {value: 1, label: '岗位角色', children: []},
                {value: 2, label: '学习计划', children: []},
                {value: 3, label: '专题', children: []},
            ],
            cascader: '',
            listForm: {
                companyId: this.$store.state.my.company_id,
            },
        };
    },
    methods: {
        formatTime(timestamp) {
            return timestamp ? new TimeFormats().convertTime('', timestamp) : '';
        },
        onSubmit() {
            this.form.page = 1;
            this.fetchData();
        },
        onResetFilters() {
            this.$refs.form.resetFields();
        },
        onCurrentChange(val) {
            this.form.page = val;
            this.fetchData();
        },
        onPageSizeChange(val) {
            this.form.size = val;
            this.form.page = 1;
            this.fetchData();
        },
        fetchData() {
            this.loading = true;
            API.get('mission', {params: this.form}).then((res) => {
                this.data = res.content;
                this.totalElements = res.pagination.total;
            }).finally(() => {
                this.loading = false;
            });
        },
        onEditClick({id}) {
            this.$router.push({
                name: 'MissionManage.Add',
                params: { id: id },
            });
        },
        onAddClick() {
            this.$router.push({
                name: 'MissionManage.Add',
            });
        },
        onDeleteClick(row) {
            if (row.status) {
                $ele.$message.error('先对行动清单下架后才进行删除操作');
                return;
            }
            $ele.$confirm('是否删除此行动清单', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API.delete(`mission/${row.id}`, {
                }).then(() => {
                    $ele.$message.success('删除成功');
                    this.fetchData();
                }).finally(() => {
                    this.loading = false;
                });
            }).catch(() => { });
        },
        onPublishClick(row) {
            const content = row.status ? '是否下架此行动清单' : '是否上架行动清单';
            const requestStatus = !row.status;
            $ele.$confirm(content, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API.put(`mission/${row.id}/${requestStatus}`).then(() => {
                    $ele.$message.success('操作成功');
                    this.fetchData();
                }).finally(() => {
                    this.loading = false;
                });
            }).catch(() => { });
        },
        fetchLabel() {
            API.get('label/group', {params: this.listForm}).then((res) => {
                this.courseOptions = res.courses;
                res.labels.map((val) => {
                    const data = this.courseOptions.filter((v) => v.label_id === val.value);
                    val.children = data;
                    if (val.type) {
                        val.types = JSON.parse(val.type);
                        val.types.map((type) => {
                            this.labelGroup[type - 1].children.push(val);
                            return type;
                        });
                    }
                    return val;
                });

                const { courseId, labelType, labelId } = this.form;
                for (const val of this.labelGroup) {
                    if (val.value === labelType && labelType) {
                        this.formCourseId = [labelType];
                        break;
                    }
                    const secondList = val.children || [];
                    for (const item of secondList) {
                        if (item.value === labelId && labelId) {
                            this.formCourseId = [val.value, labelId];
                            break;
                        }
                        const thirdList = item.children || [];
                        for (const inVal of thirdList) {
                            if (inVal.value === courseId && courseId) {
                                this.formCourseId = [val.value, item.value, courseId];
                                break;
                            }
                        }
                    }
                }
            });
        },
        indexMethod(index) {
            return new IndexNumber()
                .getIndex(this.totalElements, this.form.page, this.form.size, index);
        },

        // 级联选择器选择
        handleChange(value) {
            if (value.length === 3) {
                this.form.courseId = value[2];
                this.form.labelType = '';
                this.form.labelId = '';
            } else if (value.length === 1) {
                this.form.courseId = '';
                this.form.labelType = value[0];
                this.form.labelId = '';
            } else if (value.length === 2) {
                this.form.labelType = '';
                this.form.courseId = '';
                this.form.labelId = value[1];
            } else {
                this.form.courseId = '';
            }
            this.onSubmit();
        },
        onResetForm() {
            this.form.courseId = '';
            this.form.status = '';
            this.form.labelType = '';
            this.form.labelId = '';
            this.$refs.mycascader.clearSelect();
            this.formCourseId = '';
            this.fetchData();
        },
    },
    mounted() {
        this.fetchData();
        this.fetchLabel();
    },
};
</script>

<style lang="scss">
.achievement-list-page {
    .filter {
        .input-width {
            width: 220px;
        }
    }
    .logo {
        width: 60px;
        height: 60px;
    }
    .footer {
        height: 44px;
        background: #f7f7f7;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-left: 20px;
        padding-right: 20px;
    }
    .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;
    }
}
</style>
